from PIL import Image


def resize_keep_ratio(image_pil, width, height):
    ratio_w = width / image_pil.width
    ratio_h = height / image_pil.height
    if ratio_w < ratio_h:
        resize_width = width
        resize_height = round(ratio_w * image_pil.height)
    else:
        resize_width = round(ratio_h * image_pil.width)
        resize_height = height
    image_resize = image_pil.resize((resize_width, resize_height), Image.ANTIALIAS)
    background = Image.new('RGBA', (width, height), (255, 255, 255, 255))
    offset = (round((width - resize_width) / 2), round((height - resize_height) / 2))
    background.paste(image_resize, offset)
    return background.convert('RGB')


def paste_image(base_img, front_img, box_b, keep_ratio=False):
    if keep_ratio:
        region = resize_keep_ratio(front_img, box_b[2] - box_b[0], box_b[3] - box_b[1])

    else:
        region = front_img.resize((box_b[2] - box_b[0], box_b[3] - box_b[1]))

    base_img.paste(region, box_b)
    return base_img


if __name__ == '__main__':
    base_img = Image.open('data/a1.png')
    front_img = Image.open('data/a2.png')
    box_b = (0, 0, 320, 337)
    new_img = paste_image(base_img, front_img, box_b, True)
    new_img.save('./out.png')

